package com.bytz.modules.cms.user.schedule;

import cn.hutool.core.bean.copier.BeanCopier;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytz.common.exception.BytzBootException;
import com.bytz.common.system.vo.LoginUser;
import com.bytz.common.util.SecurityUtils;
import com.bytz.modules.bpm.client.model.StartProcessResult;
import com.bytz.modules.cms.order.constants.OrderFlowConstants;
import com.bytz.modules.cms.user.entity.EcAudit;
import com.bytz.modules.cms.user.model.EcAuditSaveRo;
import com.bytz.modules.cms.user.service.IEcAuditFlowService;
import com.bytz.modules.cms.user.service.IEcAuditService;
import com.bytz.modules.system.service.ISysUserService;
import com.bytz.modules.system.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: cms-backend
 *
 * @description:
 *
 * @author: KyleWang
 *
 * @create: 2022-11-01 17:39
 **/
@Component
@Slf4j
public class EcStartProcessSchedule implements Job {

    @Autowired
    IEcAuditService ecAuditService;
    @Autowired
    IEcAuditFlowService ecAuditFlowService;



    @Autowired
    ISysUserService userService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        List<EcAudit> list = ecAuditService.lambdaQuery().isNull(EcAudit::getProcInstId).list();
        IPage<SysUserVo> userByRole = userService.getUserByRole(new Page<>(1, 1,false), null, OrderFlowConstants.EcFlowProperty.AUDIT_ROLE, null, null);
        if (CollectionUtils.isEmpty(userByRole.getRecords())) {
            throw new BytzBootException("找不到EC审批处理人");
        }
        SysUserVo sysUser = userByRole.getRecords().get(0);
        LoginUser loginUser = BeanCopier.create(sysUser, new LoginUser(), CopyOptions.create().ignoreNullValue()).copy();
        SecurityUtils.setLoginUser(loginUser);

        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(audit -> {
                EcAuditSaveRo auditSaveRo = BeanCopier.create(audit, new EcAuditSaveRo(), CopyOptions.create()).copy();
                try {
                    StartProcessResult ecStartProcessResult = ecAuditFlowService.startProcess(auditSaveRo, null, loginUser);
                    log.info("流程发起成功 ecAudit id:{};result:{}", auditSaveRo.getId(), ecStartProcessResult);
                } catch (Exception e) {
                    log.error(String.format("发起Ec审批流程失败 ecAuditId:%s", auditSaveRo.getId()), e);
                }
            });
        }
    }
}